<template>
  <div class="login-container">
    <el-form ref="login" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left">
      <div class="title-container">
        <h3 class="title">Login Form</h3>
      </div>
      <div class="login-form-form">
        <el-form-item prop="account">
          <el-input v-model="loginForm.account" size="large" placeholder="请输入账号" name="account" type="text" tabindex="1" auto-complete="on" @keyup.enter="handleLogin" />
        </el-form-item>
        <el-form-item prop="password">
          <!-- <el-input v-model="loginForm.password" placeholder="请输入密码" show-password @keyup.enter.native="handleLogin">
            <i slot="prefix" class="el-input__icon el-icon-lock" />
          </el-input> -->
          <el-input v-model="loginForm.password" type="password" size="large" placeholder="请输入密码" show-password @keyup.enter="handleLogin" />
        </el-form-item>
        <el-form-item>
          <div style="display: flex; justify-content: space-between">
            <el-checkbox v-model="state.checkPwd">记住密码</el-checkbox>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button round size="large" :loading="state.loading" type="primary" @click.prevent="handleLogin">登录</el-button>
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import Cookies from 'js-cookie'
import CryptoJs from 'crypto-js'
import { onMounted, reactive, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useStore } from '@/store/index'
import Service from '@/api/login'

const store = useStore()
const route = useRoute()
const router = useRouter()
const login = ref()
const state = reactive({
  checkPwd: false,
  loading: false,
  redirect: ''
})
const loginForm = reactive({
  account: '',
  password: ''
})
const validateAccount = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('账号不能为空'))
  } else if (value.length < 5) {
    callback(new Error('请输入至少由数字、英文、汉语组成的5位账号'))
  } else {
    callback()
  }
}
const validatePassword = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('密码不能为空'))
  } else if (value.length < 5) {
    callback(new Error('请输入至少由数字、英文组成的5位密码'))
  } else {
    callback()
  }
}
const loginRules = reactive({
  account: [{ required: true, trigger: 'blur', validator: validateAccount }],
  password: [{ required: true, trigger: 'blur', validator: validatePassword }]
})
onMounted(() => {
  // note:判断Cookies是否有数据
  const account = Cookies.get('account')
  const password = Cookies.get('password')
  if (account && password) {
    // note:密码解密以及数据回填
    loginForm.account = account
    loginForm.password = CryptoJs.AES.decrypt(password, 'userPwd').toString(CryptoJs.enc.Utf8)
    state.checkPwd = true
  } else {
    state.checkPwd = false
  }
})
watch(
  () => route,
  (route) => {
    if (Object.getOwnPropertyNames(route.query).length) {
      state.redirect = route.query.redirect ? route.query.redirect.toString() : ''
    }
  },
  { immediate: true, deep: true }
)
const handleLogin = () => {
  login.value.validate((valid: any) => {
    if (valid) {
      state.loading = true
      Service.postLogin(loginForm)
        // note:成功处理
        .then((res) => {
          state.loading = false
          if (res.code === '200') {
            store.dispatch('userModule/login', res.data).then(() => {
              // note:判断是否有选中记住密码
              if (state.checkPwd) {
                // note:保存账号以及密码加密,此处userPwd为秘钥
                Cookies.set('account', loginForm.account.trim(), {
                  expires: 30
                })
                Cookies.set('password', CryptoJs.AES.encrypt(loginForm.password, 'userPwd'), { expires: 30 })
              } else {
                Cookies.remove('account')
                Cookies.remove('password')
              }
              ElMessage({
                type: 'success',
                message: '登录成功'
              })
              router.replace({ path: state.redirect || '/' })
            })
          }
        })
        // note:错误处理
        .catch(() => {
          state.loading = false
        })
    }
  })
}
</script>

<style lang="scss" scoped>
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */
$cursor: #fff;
$light_gray: #203892;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 100%;
    ::v-deep .el-input__wrapper {
      width: 100%;
      border-radius: 47px;
    }
    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 48px;
      caret-color: $cursor;

      &:-webkit-autofill {
        -webkit-text-fill-color: $cursor !important;
      }
    }
    ::v-deep .el-input__inner {
      border-radius: 24px;
      color: $light_gray;
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$dark_gray: #889aa4;
$light_gray: #203892;

.login-container {
  min-height: 100%;
  width: 100%;
  background: url('../../assets/login-bg.jpg') no-repeat;
  overflow: hidden;
  display: flex;
  justify-content: end;
  padding: 50px;
  .login-form {
    background: white;
    width: 520px;
    height: 50%;
    max-width: 100%;
    align-self: center;
    padding: 135px 60px;
    .el-button {
      width: 100%;
    }
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
